package com.lh.common.exception;

import com.lh.common.pojo.ExceptionField;
import com.lh.common.pojo.ExceptionResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liuhe
 * @date 2020/07/06
 */
@ControllerAdvice
@ResponseBody
public class WebExceptionHandler {

    /**
     * RestMapping 传参校验异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<ExceptionResponse> methodArgumentNotValidExceptionHandler(HttpServletRequest request, HttpServletResponse response, MethodArgumentNotValidException ex) {
        List<ExceptionField> exceptionFields = buildExceptionFields(request, ex.getBindingResult().getFieldErrors());
        ExceptionResponse exceptionResponse = new ExceptionResponse("120000", "参数校验失败", null, exceptionFields);
        return new ResponseEntity<ExceptionResponse>(exceptionResponse, null, HttpStatus.NOT_ACCEPTABLE);
    }

    private List<ExceptionField> buildExceptionFields(HttpServletRequest request, List<FieldError> fieldErrors) {
        List<ExceptionField> exceptionFields = new ArrayList<>();
        for (FieldError error : fieldErrors) {
            String fieldName = error.getField();
            Object fieldValue = error.getRejectedValue();
            String objectName = error.getObjectName();
            String message = error.getDefaultMessage();
            String location;
            if (null != request.getHeader(fieldName)) {
                location = "header";
            } else {
                location = "body";
            }
            ExceptionField exceptionField = new ExceptionField(objectName, location, fieldName, "invalidParameter", error.getDefaultMessage());

            exceptionFields.add(exceptionField);
        }
        return exceptionFields;
    }
}
